require 'socket'

class HTTPSocket
  def initialize(sHost, iPort)
    @sHost = sHost;
    @iPort = iPort;

    @hHeaders = {}
    AddHeader('Connection','Close')  #We wont need to do any pipelining
    AddHeader('Host', sHost)
  end

  def AddHeader(sKey, sValue)
    @hHeaders[sKey.chomp]=sValue.chomp
  end

  def RemoveHeader(sKey)
    @hHeaders.delete(sKey)
  end

  def GetURL(sURL)
    sReq = TagHeaders("GET #{sURL} HTTP/1.1\n");
	  
    @sSocket = TCPSocket::new(@sHost,@iPort)
    @sSocket.send(sReq,0)

    hHeaders = ReceiveHeader()
    if(hHeaders.has_key? "Content-Length")
		iLen = hHeaders["Content-Length"].to_i
		iRead = 0
		bBuff = ""
		while(iRead < iLen)
			bBuff += @sSocket.recv(iLen-iRead)
			iRead = bBuff.length
		end
	end
    @sSocket.close
	return bBuff
  end

  def TagHeaders(sReq)
	@hHeaders.each{|key, value|
		sReq += key +': '+value+"\n"
	}
	return "#{sReq}\r\n\r\n"
  end

  def ReceiveHeader()
	sHead = ""
	begin
		sHead += @sSocket.recv(1)
	end while(!sHead.include? "\r\n\r\n")
	hHeaders = ProcessHeaders(sHead);

	return hHeaders
  end

  def ProcessHeaders(sHead)
	hHeaders = {}
	sHead.each{|line|
		saHeadParts = line.split(/: /)
		hHeaders[saHeadParts[0]]=saHeadParts[1]
	}
	return hHeaders
  end
end